package io.hilo.example.account.service;

import java.util.Date;

import org.jretty.apibase.Request;
import org.jretty.apibase.Result;
import org.springframework.beans.factory.annotation.Autowired;

import org.hilo.boot.core.UT;
import org.hilo.boot.core.util.ValidatorUtils;
import io.hilo.example.account.api.UserService;
import io.hilo.example.account.dms.DemoUserEntityDms;
import io.hilo.example.account.dto.user.AddUserReq;
import io.hilo.example.account.dto.user.AddUserRes;
import io.hilo.example.account.dto.user.ChangePasswordReq;
import io.hilo.example.account.dto.user.ChangePasswordRes;
import io.hilo.example.account.dto.user.UpdateUserReq;
import io.hilo.example.account.dto.user.UpdateUserRes;
import io.hilo.example.account.entity.UserEntity;

/**
 * 
 * @author zollty
 * @since 2018年6月19日
 */
@com.alibaba.dubbo.config.annotation.Service
public class UserServiceImpl implements UserService {
    @Autowired
    private DemoUserEntityDms userDms;

    @Override
    public Result<AddUserRes> addUser(Request<AddUserReq> req) {
        AddUserReq params = req.getData();
        ValidatorUtils.validateEntity(params);

        UserEntity user = UT.Ref.fieldCloneByName(params, new UserEntity());
        user.setPassword(user.getPassword());
        Date now = new Date();
        user.setCreateDate(now);
        user.setModifyUserid(user.getCreateUserid());
        user.setModifyDate(now);
        
        userDms.addUser(user);
        
        return Result.success(new AddUserRes(1000L));
    }
    
    @Override
    public Result<UpdateUserRes> updateUser(Request<UpdateUserReq> req) {
        UpdateUserReq params = req.getData();
        ValidatorUtils.validateEntity(params);
        
        UserEntity user = UT.Ref.fieldCloneByName(params, new UserEntity());
        if(UT.Str.isNotBlank(user.getPassword())) {
            user.setPassword(user.getPassword());
        } else {
            user.setPassword(null);
        }
        user.setModifyDate(new Date());
        userDms.updateUser(user);
        
        return Result.success();
    }

    @Override
    public Result<ChangePasswordRes> changePassword(Request<ChangePasswordReq> req) {
        ChangePasswordReq params = req.getData();
        ValidatorUtils.validateEntity(params);

        Result<?> ret = userDms.checkPassword(params.getUserId(), params.getOldPassword());
        if (ret.isFailed()) {
            return Result.fail(ret.getCode(), ret.getMsg());
        }

        // 更新密码
        userDms.updatePassword(params.getUserId(), params.getNewPassword());

        return Result.success();
    }

}
